<template>
  <div>
    <el-descriptions :column="6" :size="size" border :labelStyle="labelStyle">
      <el-descriptions-item label="任务名称" :contentStyle="contentStyle1">{{ task.title }}</el-descriptions-item>
      <el-descriptions-item label="发布人" :contentStyle="contentStyle">{{ task.releaseBy }}</el-descriptions-item>
      <el-descriptions-item label="发布时间" :contentStyle="contentStyle2">{{ task.createTime }}</el-descriptions-item>
      <el-descriptions-item label="任务负责人" :contentStyle="contentStyle">{{ task.reportBy }}</el-descriptions-item>
      <el-descriptions-item label="项目号" :contentStyle="contentStyle">{{ task.projectSn }}</el-descriptions-item>
      <el-descriptions-item label="汇报频率" :contentStyle="contentStyle">{{ task.frequency }}</el-descriptions-item>
      <el-descriptions-item :span="3" label="任务内容">
        <el-table :show-header="headerVisible" :size="size" :data="task.contentSummaries" empty-text=" "
                  style="margin: 0;">
          <el-table-column type="index"></el-table-column>
          <el-table-column prop="contentSummary"></el-table-column>
        </el-table>
      </el-descriptions-item>
      <el-descriptions-item :span="3" label="附件">
        <el-table :size="size" :data="task.releaseAttachments" :show-header="headerVisible" empty-text="无附件">
          <el-table-column type="index"></el-table-column>
          <el-table-column prop="filePath">
            <template slot-scope="scope">
              <el-link :href="scope.row.filePath" target="_blank">{{ scope.row.filePath.split('/').pop() }}</el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-descriptions-item>
    </el-descriptions>
    <div ref="gantt" style="width: 100%; margin: 20px 0; height: auto;"></div>
    <div v-for="(subTask ,index) in subTasks"
         style="border-top: 1px solid #cccccc; border-bottom: 1px solid #cccccc; border-radius: 5px; padding: 5px 0px;">
      <el-form :model="subTask" size="mini" label-position="top">
        <el-row :gutter="20">
          <el-col :span="9">
            <el-form-item label="任务名称">
              <el-input v-model="subTask.title"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="负责人">
              <el-cascader
                  :options="optionsHeader"
                  :props="{ expandTrigger: 'hover' }" @change="handleCascaderChange($event,index)">
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="任务分类">
              <el-select v-model="subTask.categoryId" placeholder="请选择" style="width: 100%">
                <el-option
                    v-for="item in optionsTask"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="项目号">
              <el-input v-model="subTask.projectSn"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="9">
            <el-form-item label="起止时间">
              <el-date-picker style="width: 100% "
                              v-model="subTask.time"
                              type="daterange"
                              range-separator="至"
                              start-placeholder="开始日期"
                              end-placeholder="结束日期"
                              @change="updateSubTaskTime(index)">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="负责人是否汇报">
              <el-radio-group v-model="radio1" size="mini">
                <el-radio-button label="是"></el-radio-button>
                <el-radio-button label="否"></el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="汇报频率" v-if="radio1==='是'">
              <el-radio-group v-model="subTask.frequency" size="small" style="text-color:#409EFF ">
                <el-radio-button label="天"></el-radio-button>
                <el-radio-button label="周"></el-radio-button>
                <el-radio-button label="月"></el-radio-button>
                <el-radio-button label="季"></el-radio-button>
                <el-radio-button label="年"></el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="14">
        <el-form-item label="内容" style="width: 100%">
          <el-table :data="subTask.contentSummaries" border :show-header="false">
            <el-table-column type="index"></el-table-column>
            <el-table-column>
              <template slot-scope="scope">
                <el-input v-model="scope.row.contentSummary" placeholder="请输入内容"></el-input>
              </template>
            </el-table-column>
            <el-table-column  width="150px">
              <template slot-scope="scope">
                <div style="display: flex; align-items: center; justify-content: space-around">
                  <el-button @click="notice()" slot="append" type="text" size="small"><i class="el-icon-alarm-clock
"></i></el-button>
                  <el-button @click="addSubTaskContentItem(index, scope.$index)" type="text" size="small">
                    <i class="el-icon-plus"></i>
                  </el-button>
                  <el-button @click="deleteSubTaskContentItem(index, scope.$index)" type="text" size="small"
                             v-if="subTask.contentSummaries.length > 1">
                    <i class="el-icon-minus"></i>
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="附件">
              <el-upload
                  class="upload-demo"
                  :action="uploadAction"
                  multiple
                  :on-success="(response, file, fileList) => handleSuccess(response, file, fileList, index)"
                  :show-file-list="false">
                <el-button><i class="el-icon-paperclip"></i></el-button>
              </el-upload>
            </el-form-item>
          </el-col>
            <el-col :span="7">
              <el-form-item label="/">
                <el-tag
                    v-for="item in subTasks[index].subTaskFileList"
                    :key="item.filePath"
                    closable
                    @close="handleRemove(item,index)">
                  <el-link :href="item.filePath" target="_blank">{{
                      extractFileName(item.filePath)
                    }}
                  </el-link>
                </el-tag>
              </el-form-item>

            </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item>
              <el-button type="text" :size="size" style="color:#ebb563" @click="deleteSubTaskItem(index)">删除</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-button type="sucess" :size="size" style="margin: 10px 0; color:#ebb563" @click="addSubTaskItem">添 加</el-button>
    <el-button type="warning" :size="size" style="margin: 10px 20px" @click="releaseSubTask">发 布</el-button>
  </div>
</template>

<script>

import {gantt} from "dhtmlx-gantt";
import moment from 'moment';

export default {
  name: "SubTask",
  data() {
    return {
      task: {},
      uploadAction: `${process.env.VUE_APP_API_BASE_URL}/file/upload`,
      subTasks: [{
        title: '',
        categoryId: '',
        projectSn: '',
        contentSummaries: [{taskContentId: '', contentSummary: ''}],
        startTime: '',
        endTime: '',
        reportBy: '',
        frequency: '周',
        attachment: [{taskId: '', filePath: '', source: ''}],
        reportCount: '',
        time: [],
        subTaskFileList: [],
      }],

      headerVisible: false,
      size: "mini",
      radio1: '是',
      optionsHeader: [
        {
          label: '市场部',
          children: [
            {value: '王豪', label: '王豪'}, {value: '郭晓娟', label: '郭晓娟'}, {value: '查苏娜', label: '查苏娜'},
            {value: '柴三朋', label: '柴三朋'}, {value: '魏滨', label: '魏滨'}, {value: '刘波', label: '刘波'},
            {value: '齐庆龙', label: '齐庆龙'}, {value: '李海军', label: '李海军'}, {value: '海泽涛', label: '海泽涛'},
            {value: '李振坤', label: '李振坤'}, {value: '郭远航', label: '郭远航'}, {value: '李富强', label: '李富强'},
          ]
        },
        {
          label: '设备部',
          children: [
            {value: '崔瑾', label: '崔瑾'}, {value: '李艳', label: '李艳'},
            {value: '郭俊山', label: '郭俊山'}, {value: '汤严', label: '汤严'},
            {value: '徐飞', label: '徐飞'}, {value: '陆彦臻', label: '陆彦臻'},
            {value: '张正权', label: '张正权'}, {value: '杨海涛', label: '杨海涛'}, {value: '高宏宇', label: '高宏宇'},
            {value: '王进', label: '王进'}, {value: '栾晓辉', label: '栾晓辉'}, {value: '孟炜', label: '孟炜'}
          ]
        },
        {
          label: '工艺技术部',
          children: [
            {value: '赵华夏', label: '赵华夏'}, {value: '邱宇', label: '邱宇'},
            {value: '王怡嵩', label: '王怡嵩'}, {value: '赵春雨', label: '赵春雨'},
            {value: '罗鹏宇', label: '罗鹏宇'}, {value: '王松', label: '王松'},
          ]
        },
        {
          label: '财务部',
          children: [
            {value: '邴丽娜', label: '邴丽娜'}, {value: '吴凤娥', label: '吴凤娥'},
            {value: '李颖頔', label: '李颖頔'}, {value: '郭乐安', label: '郭乐安'},
          ]
        },
        {
          label: '办公室',
          children: [
            {value: '孟强', label: '孟强'}, {value: '董继红', label: '董继红'}, {value: '柴鹏', label: '柴鹏'},
            {value: '任婷', label: '任婷'}, {value: '巩新蕾', label: '巩新蕾'}, {value: '安宝亮', label: '安宝亮'},
          ]
        },
      ],
      optionsTask: [
        {
          value: '1',
          label: '项目类'
        }, {
          value: '2',
          label: '行政类'
        }
      ],
      labelStyle: {
        'width': '7%',
        'color': '#909399',
        'font-size': '14px',
        'font-weight': 'bold'
      },
      contentStyle1: {
        'width': '16%',
        'word-break': 'break-all'
      },
      contentStyle2: {
        'width': '13%',
        'word-break': 'break-all'
      },
      contentStyle: {
        'width': '7%',
        'word-break': 'break-all'
      }
    }
  },
  computed: {
    reportCount() {
      return this.subTasks.map(subTask => {
        if (!subTask.time[0] || !subTask.time[1] || !subTask.frequency) {
          return 0; // 如果没有设置时间或频率，则汇报次数为0
        }
        const startDate = new Date(subTask.time[0]);
        const endDate = new Date(subTask.time[1]);
        const diffTime = Math.abs(endDate - startDate);
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        const adjustedDiffDays = diffDays === 0 ? 1 : diffDays; // 确保至少为1天

        switch (subTask.frequency) {
          case '天':
            return adjustedDiffDays;
          case '周':
            return Math.ceil(adjustedDiffDays / 7);
          case '月':
            return Math.ceil(adjustedDiffDays / 30);
          case '季':
            return Math.ceil(adjustedDiffDays / 90);
          case '年':
            return Math.ceil(adjustedDiffDays / 365);
          default:
            return 0;
        }
      });
    }
  },
  methods: {
    initGantt() {
      this.$nextTick(() => {
        const task = this.task
        const ganttConfig = this.$store.state.ganttConfig
        gantt.i18n.setLocale(ganttConfig.locale);
        gantt.config.scale_height = ganttConfig.scale_height;
        gantt.config.scales = ganttConfig.scales;
        gantt.config.xml_date = ganttConfig.xml_date;
        gantt.config.row_height = ganttConfig.row_height;
        gantt.config.show_markers = ganttConfig.show_markers;
        gantt.config.autosize = ganttConfig.autosize;
        gantt.config.readonly = ganttConfig.readonly;
        gantt.config.show_grid = ganttConfig.show_grid;
        gantt.templates.task_text = ganttConfig.task_text_template
        gantt.plugins({
          marker: true
        })
        gantt.init(this.$refs.gantt);
        gantt.config.columns = [];
        gantt.clearAll();
        var dateToStr = gantt.date.date_to_str(gantt.config.task_date);
        var today = new Date()
        gantt.addMarker({
          start_date: today,
          css: "today_line",
          text: "今日",
          title: "今日" + dateToStr(today)
        });
        gantt.parse({
          data: [
            {
              id: task.id,
              start_date: task.start_date,
              end_date: task.end_date,
              progress: task.progress,
              color: this.getColorByStatus(task.statusName),
              projectSn: task.projectSn,
              statusName: task.statusName,
            }
          ]
        });

      });
    },
    getColorByStatus(statusName) {
      switch (statusName) {
        case '进行中':
          return "rgba(125,193,90,0.79)"; // 浅绿色
        case '已完成':
          return "rgba(189,190,188,0.92)"; // 灰色
        case '已延期':
          return "rgba(200,186,93,0.8)"; // 橙色
      }
    },
    notice() {
      alert("已增加提醒")
    },
    updateSubTaskTime(taskIndex) {
      this.subTasks[taskIndex].startTime = moment(this.subTasks[taskIndex].time[0]).format('YYYY/MM/DD HH:mm:ss')
      this.subTasks[taskIndex].endTime = moment(this.subTasks[taskIndex].time[1]).format('YYYY/MM/DD HH:mm:ss')
    },
    handleCascaderChange(value, taskIndex) {
      this.subTasks[taskIndex].reportBy = value[value.length - 1];
    },
    handleSuccess(response, file, fileList, taskIndex) {
      console.log(response)
      const attachment = {
        name:file.name,
        filePath: response.data,
        source: '发布时'
      };
      this.subTasks[taskIndex].attachment.push(attachment);
      this.subTasks[taskIndex].subTaskFileList.push(attachment)
    },
    handleRemove(attachment,taskIndex) {
      this.$confirm('确定要删除这个文件吗?', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.subTasks[taskIndex].subTaskFileList.findIndex(item => item.filePath === attachment.filePath);
        if (index !== -1) {
          this.subTasks[taskIndex].subTaskFileList.splice(index, 1);
        }
      }).catch(() => {
        // 用户取消删除操作
        this.$message({
          type: 'info',
          message: '删除取消'
        });
      });
    },
    addSubTaskContentItem(taskIndex, summaryIndex) {
      this.subTasks[taskIndex].contentSummaries.push({contentSummary: ''})
    },
    deleteSubTaskContentItem(taskIndex, summaryIndex) {
      if (this.subTasks[taskIndex].contentSummaries.length != 1)
        this.subTasks[taskIndex].contentSummaries.splice(summaryIndex, 1)
      else alert("至少需要保留一条任务吧~~")
    },
    addSubTaskItem() {
      const category = this.optionsTask.find(c => c.label === this.task.categoryName);
      this.subTasks.push({
        parentId: this.task.id,
        title: '',
        categoryId: category.value,
        projectSn: this.task.projectSn,
        contentSummaries: [{contentSummary: ''}],
        startTime: '',
        endTime: '',
        reportBy: '',
        frequency: '周',
        attachment: [],
        subTaskFileList: [],
        time: [],
      })
    },
    deleteSubTaskItem(index) {
      if (this.subTasks.length > 1) {
        this.subTasks.splice(index, 1)
      } else {
        alert("至少需要保留一条")
      }
    },
    releaseSubTask() {
      const releaseTaskDTO = this.subTasks.map((subTask, index) => ({
        ...subTask,
        parentId: this.task.id,
        reportCount: this.reportCount[index]
      }))
      console.log(releaseTaskDTO)
      this.$http.post("/task/releaseSubTask", releaseTaskDTO).then((response) => {
        if (response.data.code == 1) {
          this.$message({type: "success", message: "发布完成:", showClose: true})
          console.log(`发送任务数据:${releaseTaskDTO}`)
        } else {
          this.$message({type: "error", message: "发布失败", showClose: true})
        }
      })
    },
    extractFileName(path) {
      return path.substring(path.lastIndexOf('/') + 1);
    }
  },
  mounted() {
    this.task = this.$store.state.currentTask
    console.log("从vuex中获取的数据为："+JSON.stringify(this.task, null, 2))
    const category = this.optionsTask.find(c => c.label === this.task.categoryName)
    if (category) {
      this.subTasks.forEach(subTask => {
        subTask.categoryId = category.value
      })
    }
    this.subTasks.forEach(subTask => {
      subTask.projectSn = this.task.projectSn
    })
    this.initGantt()
  }
}

</script>

<style scoped>

</style>